/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.addressBook.controller;

import com.addressBook.bean.UserInfo;
import com.addressBook.tools.CommonPhotoTools;
import com.addressBook.util.AllUtil;
import com.fxexperience.javafx.animation.FlipOutYTransition;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.animation.Transition;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseDragEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javax.swing.JFileChooser;

/**
 * FXML Controller class
 *
 * @author Administrator
 */
public class PersonInfoController implements Initializable {

    private static PersonInfoController instance;

    public static PersonInfoController getPersonInfoController() {
        return instance;
    }
//    private UserInfo saveUser = new UserInfo();
    @FXML
    private ImageView picture;
    @FXML
    private Label name;
    @FXML
    private TextField xing;
    @FXML
    private TextField HomeTel;
    @FXML
    private TextField WorkTel;
    @FXML
    private TextField Email;
    @FXML
    private TextField Note;
    @FXML
    private Button save;
    @FXML
    private ImageView back;
    @FXML
    private ListView<String> tellist;
    @FXML
    private TextField ming;
    @FXML
    private ImageView addHomeTel;
    @FXML
    private ImageView addEmail;
    @FXML
    private ListView<String> listEmail;
    @FXML
    private DatePicker birthday;
    @FXML
    private TextField contry;
    @FXML
    private TextField shengfen;
    @FXML
    private TextField city;
    @FXML
    private TextField mailcode;
    @FXML
    private TextArea street;
    @FXML
    private TextField danwei;
    @FXML
    private TextField bumen;
    @FXML
    private TextField zhiwu;
    @FXML
    private ImageView addWorkTel;
    @FXML
    private ListView<String> listWorkTel;
    @FXML
    private TextField fax;
    @FXML
    private TextField countryF;
    @FXML
    private TextField shengfenF;
    @FXML
    private TextField cityF;
    @FXML
    private TextField codeF;
    @FXML
    private TextArea streetF;
    @FXML
    private TextField telF;
    @FXML
    private ImageView addTelF;
    @FXML
    private ListView<String> listTelF;
    @FXML
    private TextField web;
    @FXML
    private TextField MSN;
    @FXML
    private TextField qq;
    @FXML
    private TextField emailSp;
    @FXML
    private ImageView addEmailS;
    @FXML
    private ListView<String> listEmailSp;

    ArrayList<String> HomeTels = new ArrayList<String>();
    ArrayList<String> WorkTels = new ArrayList<String>();
    ArrayList<String> HomeEmails = new ArrayList<String>();
    ArrayList<String> WorkEmails = new ArrayList<String>();

    @FXML
    private ImageView changePicture;
    @FXML
    private Label baseLabel;
    @FXML
    private Label workInfoLabel;
    @FXML
    private Label familiyInfoLabel;
    @FXML
    private Label webInfoLabel;
    @FXML
    private AnchorPane basePane;
    @FXML
    private AnchorPane workinfoPane;
    @FXML
    private AnchorPane familyinfoPane;
    @FXML
    private AnchorPane webinfoPane;
    @FXML
    private ChoiceBox<?> group;
    @FXML
    private Label note2;
    @FXML
    private Label editImg;
    @FXML
    private Pane imageViewCatain;

    public void setText() {
        UserInfo user = AllUtil.personBean;
        if (user != null) {
//             System.out.println("+++++++++++++++++++++++");
            //name
//            name.setText(user.getFN());
            String s = user.getN();
            String[] s1 = s.split(";");
            xing.setText(s1[0]);
            if (s1.length >= 2) {
                ming.setText(s1[1]);
            }
            name.setText(xing.getText() + ming.getText());

            //hometellist&telworklist
            for (int i = 0; i < user.getTEL().size(); i++) {
                String str = user.getTEL().get(i);
                String[] s2 = str.split(":");
                if (s2[0].equals("TYPE=CELL")) {
                    getHomeTels().add(s2[1]);
                } else {
                    getWorkTels().add(s2[1]);
                }
            }
            ObservableList<String> items;
            items = FXCollections.observableArrayList(getHomeTels());
            tellist.setItems(items);
            items = FXCollections.observableArrayList(getWorkTels());
            listWorkTel.setItems(items);

            //emaillist
            for (int i = 0; i < user.getEMAIL().size(); i++) {
                String str = user.getEMAIL().get(i);
                String[] s2 = str.split(":");
                if (s2[0].equals("TYPE=CELL")) {
                    HomeEmails.add(s2[1]);
                } else {
                    WorkEmails.add(s2[1]);
                }
            }
            ObservableList<String> EmailList;
            EmailList = FXCollections.observableArrayList(HomeEmails);
            listEmail.setItems(EmailList);
            EmailList = FXCollections.observableArrayList(WorkEmails);
            listEmailSp.setItems(EmailList);
            //brithday
            user.setBRITHDAY("2012-4-1");
            String s3 = user.getBRITHDAY();
            String[] s4 = s3.split("-");
            int year = Integer.parseInt(s4[0]);
            int month = Integer.parseInt(s4[1]);
            int day = Integer.parseInt(s4[2]);

            LocalDate date = LocalDate.of(year, month, day);
            birthday.setValue(date);
//            birthday.setConverter(new StringConverter<LocalDate>() {
//                String pattern = "";
//                DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(pattern);
//
//                {
//                    birthday.setPromptText(pattern.toLowerCase());
//                }
//
//                @Override
//                public String toString(LocalDate date) {
//                    if (date != null) {
//                        return dateFormatter.format(date);
//                    } else {
//                        return "";
//                    }
//                }
//
//                @Override
//                public LocalDate fromString(String string) {
//                    if (string != null && !string.isEmpty()) {
//                        return LocalDate.parse(string, dateFormatter);
//                    } else {
//                        return null;
//                    }
//                }
//            });
            //note
            Note.setText(user.getNOTE());
            if (user.getNOTE() == null || user.getNOTE().equals("")) {
                note2.setText("这人有点懒，还没备注，要不要帮他加一个");
            } else {
                note2.setText(user.getNOTE());
            }

            //显示图片
            byte[] buf = CommonPhotoTools.Str2byte(user.getPHOTO());
            InputStream is = new ByteArrayInputStream(buf);
            Image image = new Image(is);
            picture.setImage(image);
        }
    }

    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
        instance = this;

        baseLabel.setOnMouseClicked(new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent event) {
                workinfoPane.setVisible(false);
                familyinfoPane.setVisible(false);
                webinfoPane.setVisible(false);
                basePane.setVisible(true);
            }
        });

        workInfoLabel.setOnMouseClicked(new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent event) {

                familyinfoPane.setVisible(false);
                webinfoPane.setVisible(false);
                basePane.setVisible(false);
                workinfoPane.setVisible(true);
            }
        });

        webInfoLabel.setOnMouseClicked(new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent event) {
                workinfoPane.setVisible(false);
                familyinfoPane.setVisible(false);

                basePane.setVisible(false);
                webinfoPane.setVisible(true);
            }
        });
        familiyInfoLabel.setOnMouseClicked(new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent event) {
                workinfoPane.setVisible(false);
                webinfoPane.setVisible(false);
                basePane.setVisible(false);
                familyinfoPane.setVisible(true);
            }
        });
        back.setOnMouseClicked(new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent event) {
                UIController uc = UIController.getUIController();
                Transition trans = new FlipOutYTransition(uc.personInfoPanel);
                trans.setOnFinished(new EventHandler<ActionEvent>() {

                    @Override
                    public void handle(ActionEvent event) {
//                        Group2listController g2c=Group2listController.getGroup2listController();
//                        g2c.groud2list.setVisible(false);
//                        GroupController gc=GroupController.getGroupController();
//                        gc.groupPane.setVisible(false);
                        uc.personInfoPanel.setVisible(false);
                        uc.back2main();
                    }
                });
                trans.play();
            }
        });

        save.setOnMouseClicked(new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent event) {
                UserInfo saveUser = new UserInfo();
                if (AllUtil.personBean == null) {
                    saveUser.setEmpty(true);
                } else {
                    saveUser.setEmpty(AllUtil.personBean.isEmpty());
                }
                saveUser.setN(xing.getText() + ";" + ming.getText());
                saveUser.setFN(name.getText());
                saveUser.setNOTE(Note.getText());
                for (int i = 0; i < WorkTels.size(); i++) {
                    saveUser.getTEL().add("TYPE=WORK:" + WorkTels.get(i));
                }
                for (int i = 0; i < HomeTels.size(); i++) {
                    saveUser.getTEL().add("TYPE=HOME:" + HomeTels.get(i));
                }
                for (int i = 0; i < HomeEmails.size(); i++) {
                    saveUser.getEMAIL().add("TYPE=HOME:" + HomeEmails.get(i));
                }
                for (int i = 0; i < WorkEmails.size(); i++) {
                    saveUser.getEMAIL().add("TYPE=WORK:" + WorkEmails.get(i));
                }
                LocalDate date = birthday.getValue();
                if (date != null) {
                    saveUser.setBRITHDAY(date.toString());
                }
                if (picture.getImage() != null) {
                    saveUser.setPHOTO(AllUtil.personBean.getPHOTO());
                }
                if (AllUtil.beanArrayList == null) {
                    AllUtil.beanArrayList = new ArrayList<UserInfo>();
                }

                if (saveUser.isEmpty()) {
                    AllUtil.beanArrayList.add(saveUser);
                } else {
                    for (int i = 0; i < AllUtil.beanArrayList.size(); i++) {
                        if (AllUtil.beanArrayList.get(i).getFN().equals(saveUser.getFN())) {
                            AllUtil.beanArrayList.remove(i);
                            AllUtil.beanArrayList.add(saveUser);
                        }
                    }
                }
                UIController uc=UIController.getUIController();
                uc.sortPage();
//                System.out.println(date);
            }
        });

        addHomeTel.setOnMouseClicked(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent event) {
//                UserInfo user = AllUtil.personBean;
//                user.getTEL().add(WorkTel.getText());
                if (!HomeTel.getText().equals("")) {
                    HomeTels.add(HomeTel.getText());
                    ObservableList<String> items;
                    items = FXCollections.observableArrayList(HomeTels);
                    tellist.setItems(items);
                }
            }
        });

        addWorkTel.setOnMouseClicked(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent event) {
//                UserInfo user = AllUtil.personBean;
                if (!WorkTel.getText().equals("")) {

                    WorkTels.add(WorkTel.getText());
                    ObservableList<String> items;
                    items = FXCollections.observableArrayList(WorkTels);
                    listWorkTel.setItems(items);
                }
            }
        });

        addEmail.setOnMouseClicked(new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent event) {
                if (!Email.getText().equals("")) {

                    HomeEmails.add(Email.getText());
                    ObservableList<String> items;
                    items = FXCollections.observableArrayList(HomeEmails);
                    listEmail.setItems(items);
                }
            }
        });

        addEmailS.setOnMouseClicked(new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent event) {
                if (!emailSp.getText().equals("")) {

                    WorkEmails.add(emailSp.getText());
                    ObservableList<String> items;
                    items = FXCollections.observableArrayList(WorkEmails);
                    listEmailSp.setItems(items);
                }
            }
        });

        xing.textProperty().addListener(new ChangeListener<String>() {

            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                name.setText(xing.getText() + ming.getText());

            }
        });
        ming.textProperty().addListener(new ChangeListener<String>() {

            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                name.setText(xing.getText() + ming.getText());

            }
        });

        picture.setOnMouseClicked(new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent event) {
                editImg.setVisible(true);
            }
        });

        editImg.setOnMouseExited(new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent event) {
                editImg.setVisible(false);
            }
        });

        editImg.setOnMouseClicked(new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent event) {
                UserInfo user = AllUtil.personBean;
                if (user == null) {
                    user = new UserInfo();
                }
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setCurrentDirectory(new File("."));
                File file = null;
                if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                    file = fileChooser.getSelectedFile();
                }
                if (file != null) {
                    try {
                        user.setPHOTO(CommonPhotoTools.BASE64Encodeing(file.getPath()));
                        byte[] buf = CommonPhotoTools.Str2byte(user.getPHOTO());
                        InputStream is = new ByteArrayInputStream(buf);
                        Image image = new Image(is);
                        picture.setImage(image);
//                    String fileName = file.getName();
//                    String houxuString = fileName.substring(fileName.lastIndexOf("."));
//                    
//                    System.out.println(file.getName());
                    } catch (Exception ex) {
                        System.out.println("编码图片出错");
                        Logger.getLogger(PersonInfoController.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    editImg.setVisible(false);
                }

            }
        });
    }

    /**
     * @return the saveUser
     */
    /**
     * @return the HomeTels
     */
    public ArrayList<String> getHomeTels() {
        return HomeTels;
    }

    /**
     * @return the WorkTels
     */
    public ArrayList<String> getWorkTels() {
        return WorkTels;
    }
}
